package com.thread.lock.money.first;

/**
 * @description:
 * @author: 刘建楼
 * @create: 2021-04-20
 **/
public class DrawThread extends Thread {

    private Account account;
    // 当前取钱线程所希望取的钱数
    private double drawAmount;

    public DrawThread(String name, Account account, double drawAmount) {
        super(name);
        this.account = account;
        this.drawAmount = drawAmount;
    }

    // 当多个账户修改一个共享数据时，将涉及数据安全问题


    @Override
    public void run() {
        // 使用 account 作为同步监视器，任何线程进入下面同步代码块之前必须先获得对account账户的锁定->其他线程无法获得锁，也就无法修改他
        // 这种做法符合 ”加锁->修改->释放锁“ 的逻辑
        synchronized (account) {
            if (account.getBalance() >= drawAmount) {
                // 吐出钞票
                System.out.println(getName() + "取钱成功！吐出钞票：" + drawAmount);
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 修改余额
                account.setBalance(account.getBalance() - drawAmount);
                System.out.println("余额为:" + account.getBalance());
            } else {
                System.out.println("取钱失败！ 余额不足");
            }
        }
        // 同步代码块结束 该线程释放同步锁

    }

    public Account getAccount() {
        return account;
    }

    public void setAccount(Account account) {
        this.account = account;
    }

    public double getDrawAmount() {
        return drawAmount;
    }

    public void setDrawAmount(double drawAmount) {
        this.drawAmount = drawAmount;
    }
}
